package org.simple.framework.boot.controller;

import org.simple.framework.core.util.SimpleBeanUtil;
import org.simple.framework.data.entity.Identifiable;
import org.simple.framework.web.result.base.SimpleResult;
import org.simple.framework.web.result.exception.web.ParameterException;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import jakarta.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.security.Principal;

/**
 * 项目名称：simple-framework
 * 类名称：ModelPatchController
 * 类描述：ModelPatchController
 * 创建时间：2018/9/7
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
public interface ModelPatchController<E extends Identifiable<ID>, ID extends Serializable, M> extends ModelController<E, ID> {

    default E handlePatch(E entity, M patchModel, Principal principal, HttpServletRequest request) {
        SimpleBeanUtil.copyPropertiesIgnoreNull(patchModel, entity);
        return entity;
    }

    @PatchMapping("/{id}")
    default SimpleResult patch(@PathVariable("id") ID id, @RequestBody M patchModel, Principal principal, HttpServletRequest request) {
        E entity = getRepository().findById(id).orElseThrow(ParameterException::new);
        entity = handlePatch(entity, patchModel, principal, request);
        getRepository().save(entity);
        return SimpleResult.ok();
    }

}
